package com.procode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

public class Intnet6Activity extends Activity {
	/** Called when the activity is first created. */

	public Socket socket;
	public String adress = "85.225.53.3";
	public int port = 8989;
	private static PrintWriter out = null;
	private static BufferedReader in = null;
	private Reader reader;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final ScrollView sw;
		final EditText et;
		final TextView tv;
		Button bt;
		
		sw = (ScrollView) this.findViewById(R.id.sw);
		et = (EditText) this.findViewById(R.id.et);
		tv = (TextView) this.findViewById(R.id.tv);
		bt = (Button) this.findViewById(R.id.bt);
		
		try {
			socket = new Socket(adress, port); 
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader
					(socket.getInputStream()));
		} catch (UnknownHostException e) {
			System.err.println("Unknown host: " +adress);
			tv.setText("Unknown host: " +adress);
			//System.exit(1);
		} catch (IOException e) {
			System.err.println("Couldn't open connection to " + adress);
			tv.setText("Couldn't open connection to " + adress);
			//System.exit(1);
		}
		
		bt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	out.println(et.getText().toString());
            	tv.append(et.getText().toString() + "\n");
            	et.setText(""); //wipe tha text
            	sw.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

		reader = new Reader(tv, sw);
		reader.execute();
	}

	/**
    A thread that reads from keyboard and sends the line to the server.
	 */
	private class Reader extends AsyncTask<Void, Integer, Void> {

		TextView mTv;
		ScrollView mSw;
		String mMsg;
		
		public Reader(TextView tv, ScrollView sw){
			mTv = tv;
			mSw = sw;
		}


		@Override
		protected Void doInBackground(Void... arg0) {
			String msg;
			try {
				while(true){
					if((msg = in.readLine()) == null) {
						mMsg = "endOfStream";    
						//System.exit(1); 
					}else{
						System.err.println(msg);
						mMsg = msg; //read line from server and print it
					}
					this.publishProgress();
				}
			}catch(Exception e) {
				System.err.println(e.getMessage());
				//System.exit(1);
			}
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Integer... progress) {
			mTv.append(mMsg + "\n");
			mSw.fullScroll(ScrollView.FOCUS_DOWN);
			mSw.clearFocus();
		}
	}
}